<template>
    <div class="folder-home-container">
        <section class="block-sec" v-if="state.isMainDrive">
            <ul class="main-folders">
                <li
                    class="main-folder"
                    v-for="mainPath in state.driveInfo"
                    :key="mainPath"
                    @dblclick="openFolder(mainPath)">
                    <i class="iconfont icon-folder primary-color folder-icon"></i>
                    <span class="folder-name">{{ mainPath }}</span>
                </li>
            </ul>
        </section>

        <section class="block-sec right-core-global" v-else>
            <p class="back-prev">
                <span @click="backPrevious">
                    <i class="iconfont icon-back-prev"></i>
                    返回上一层:  {{ folderStore.activePath }}
                </span>
            </p>
            <ul class="into-folders right-core-global">
                <!-- v-right-click="{ fn: rightClick, args: { ...opt, $index: index } }" -->
                <li
                    class="into-folder"
                    v-for="(opt, index) in folderStore.folderInfo"
                    :key="index"
                    @dblclick="openIntoFolder(opt)"
                    v-right-click="{ fn: rightClick, args: opt, $index: index }"
                    >
                    <div class="box-item-wrap">
                        <div class="box-item-wrap-iconbox">
                            <i v-if="opt.is_dir" class="iconfont icon-folder primary-color folder-icon"></i>
                            <i v-else class="iconfont icon-unknow-file file-icon"></i>
                        </div>
                        <span v-if="!opt.isRename" :title="opt.name"  class="folder-name">{{ opt.name }}</span>
                        <el-input
                            style="width: 85px"
                            v-if="opt.isRename"
                            class="folder-name-input"
                            v-model="opt.name"
                            @dblclick.stop
                            @blur="renameBlur(opt)"
                            @keydown.enter="renameBlur(opt)"
                        />
                    </div>
                </li>
            </ul>
        </section>
    </div>
</template>

<script setup lang="ts">
import { invoke } from "@tauri-apps/api/core";
// import { currentMonitor, availableMonitors } from "@tauri-apps/api/window";
// import { WebviewWindow, getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { reactive } from "vue";
import { mapperEndSlask } from "../../utils/folder";
import { useFolderStore } from "../../store/folder";

const folderStore = useFolderStore();

const state = reactive({
    isMainDrive: true,
    // activePath: '',
    driveInfo: <any>[],
});

// 打开磁盘
const openFolder = async (mainPath: string) => {
    const folders = await getFolderInfo(mainPath)
    state.isMainDrive = false;
    folderStore.folderInfo = folders;
}

// 打开磁盘下的文件夹
const openIntoFolder = async (opt: any) => {
    const curPath = mapperEndSlask(folderStore.activePath) + opt.name
    const folders = await getFolderInfo(curPath)
    folderStore.folderInfo = folders;
}

// 返回上一步
const backPrevious = async () => {
    const curPath = folderStore.activePath.split('\\');
    if (curPath.length === 2 && !curPath[curPath.length - 1]) {
        getDrives();
        state.isMainDrive = true
        return false
    }
    curPath.pop()
    const path = curPath.join('\\');
    const rePath = path.length <= 2 ? path + '\\' : path
    const folders = await getFolderInfo(rePath)
    folderStore.folderInfo = folders;
}

const rightClick = (ev: MouseEvent, opt: any, index: number) => {
    console.log('右键点击2', opt, index)
    folderStore.showRightMenu = true;
    folderStore.rightHoverItem = { ...opt, $index: index }
    folderStore.rightMenuX = ev.clientX;
    folderStore.rightMenuY = ev.clientY;
}

const renameBlur = async (opt: any) => {
    const oldPath = mapperEndSlask(folderStore.activePath) + folderStore.rightHoverItem.name
    const newPath = mapperEndSlask(folderStore.activePath) + opt.name
    await folderStore.renameFolder(oldPath, newPath)
    const _i = folderStore.rightHoverItem.$index
    folderStore.folderInfo[_i].name = opt.name
    folderStore.folderInfo[_i].isRename = false
}

/**
 * 新窗口打开文件夹，跳转目录为：/folder_into
 */
// const openIntoWindow = async () => {
//     console.log("dblclick into window");

//     const monitorInfo = await currentMonitor();
//     const ableMonitor = await availableMonitors();
//     const currentWebviewWindow = await getCurrentWebviewWindow();

//     console.log(monitorInfo, '屏幕信息1');
//     console.log(ableMonitor, '屏幕信息2');
//     console.log(currentWebviewWindow, 'currentWebviewWindow');

//     // 创建新窗口
//     const folderWebview = await new WebviewWindow('folderWindow', {
//         url: "http://localhost:1420/#/folder_into", // 新窗口的URL
//         title: "文件夹",
//         center: true, // 是否居中显示
//         width: 800,
//         height: 600,
//         minWidth: 500, // 最小宽度
//         minHeight: 300, // 最小高度
//         resizable: true, // 是否可调整窗口大小
//         decorations: true, // 是否显示窗口控制栏
//         alwaysOnTop: false, // 是否窗口置顶
//         maximized: false, // 是否最大化
//         transparent: false, // 是否透明
//         focus: true, // 是否聚焦
//         visible: true, // 是否可见
//         closable: true, // 是否可关闭
//         theme: "light",
//         backgroundColor: "#fff",

//     });

//     folderWebview.emit('data', {
//         message: 'Hello from main window!'
//     })


//     // 监听窗口创建事件
//     folderWebview.once("tauri://created", function () {
//         console.log("监听Into窗口创建成功: into window created");
//     });

//     // 监听窗口创建失败事件
//     folderWebview.once("tauri://error", (error) => {
//         console.error("创建新窗口失败:", error);
//     });
// };

const getDrives = async (): Promise<string[]> => {
    try {
        const drives = await invoke<string[]>("get_drives");
        console.log("磁盘列表：", drives);
        state.driveInfo = drives;
        return drives;
    } catch (error) {
        console.error("获取磁盘失败：", error);
        return [];
    }
};
getDrives();

/**
 * 获取文件/文件夹信息
 * @param folderPath 文件路径
 */
const getFolderInfo = async (folderPath: string) => {
    return new Promise((resolve, reject) => {
        try {
            invoke("get_folder_info", { path: folderPath })
            .then((info) => {
                folderStore.activePath = folderPath;
                console.log('当前路径', folderStore.activePath)
                console.log("磁盘信息:", info);
                resolve(info);
            })
            .catch((error) => {
                console.error("[Try Error]: 获取磁盘信息失败:", error);
                reject(error);
            });
        } catch (error) {
            console.error("[Catch Error]: 获取磁盘信息失败:", error);
        }
    });
};
</script>

<style lang="less">
.folder-home-container {
    width: 100%;
    height: inherit;
    font-family: Arial, sans-serif;
    padding: 20px;
    .block-sec {
        height: inherit;
        .main-folders {
            height: inherit;
            display: flex;
            align-items: center;
            justify-content: center;

            .main-folder {
                margin: 30px;
                display: flex;
                align-items: center;
                justify-content: center;
                position: relative;

                .folder-icon {
                    font-size: 100px;
                    cursor: pointer;
                }

                .folder-name {
                    font-size: 18px;
                    position: absolute;
                    color: #fff;
                    cursor: pointer;
                }
            }
        }

        .back-prev {
            transition: all 0.25s;
            cursor: pointer;
            user-select: none;
            &:hover {
                color: #007bff;
                transition: all 0.25s;
            }
        }

        .into-folders {
            display: flex;
            flex-wrap: wrap;
            place-content: flex-start;

            .into-folder {
                margin: 5px 10px;
                display: flex;
                flex-direction: column;
                // justify-content: center;
                &:hover {
                    background: #f3f3f3;
                }
                &-checked {
                    background: #f3f3f3;
                }

                .folder-icon {
                    font-size: 80px;
                    cursor: pointer;
                }

                .file-icon {
                    font-size: 60px;
                    cursor: pointer;
                }

                .box-item-wrap {
                    display: flex;
                    flex-direction: column;
                    &-iconbox {
                        width: 80px;
                        height: 80px;
                        line-height: 80px;
                        text-align: center;
                    }
                }

                .folder-name {
                    width: 85px;
                    font-size: 14px;
                    color: #2f2f33;
                    cursor: pointer;
                    text-align: center;
                    // display: -webkit-box;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    // -webkit-box-orient: vertical;
                    // -webkit-line-clamp: 2;
                }
            }
        }
    }
}
</style>

<style lang="less">
.folder-name-input {
    .el-input__wrapper {
        box-shadow: none;
        border-bottom: 1px solid #0d60f0;
        border-radius: 0;
        outline: none;
        &:hover {
            border: none;
            box-shadow: none;
            border-bottom: 1px solid #0d60f0;
        }
    }
    .el-input__wrapper.is-focus {
        box-shadow: none;
    }
    input {
        font-size: 14px;
        color: #2f2f33;
        height: 13px;
        line-height: 13px;
        text-align: center;
    }
}

</style>
